import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

export default createStore({
  state: {
    isLoggedIn: false,
    user: null, // 通常，未登录时用户信息设为null而不是空字符串
    selectedFiles: [], // 新增这个属性并初始化为空数组
    parentFolderId: null, // 新增parentFolderId状态
  },
  mutations: {
    setLogin(state, user) {
      state.isLoggedIn = true;
      state.user = user;
      // 如果需要，可以在这里将user信息同步到sessionStorage
      sessionStorage.setItem("user", JSON.stringify(user));
    },
    logout(state) {
      state.isLoggedIn = false;
      state.user = null;
      state.selectedFiles = []; // 清空选中的文件数组
      // 不在这里清除sessionStorage，而是在action中做
    },
    // 更新parentFolderId
    SET_PARENT_FOLDER_ID(state, folderId) {
      state.parentFolderId = folderId;
    },
    SET_SELECTED_FILES(state, files) {
      state.selectedFiles = files;
    },

    // 添加或更新选中项
    TOGGLE_FILE_SELECTION(state, { fileId, isSelected, source }) {
      const existingFile = state.selectedFiles.find(
        (file) => file.id === fileId
      );
      if (existingFile) {
        // 如果文件已存在，则更新其选中状态
        existingFile.selected = isSelected;
      } else {
        // 否则，将新文件添加到数组中
        state.selectedFiles.push({ id: fileId, selected: isSelected, source });
      }
    },

    // 清除所有选中项
    CLEAR_SELECTED_FILES(state) {
      state.selectedFiles = [];
    },
  },
  actions: {
    login({ commit }, user) {
      commit("setLogin", user);
    },
    logout({ commit }) {
      commit("logout");
      // 在action中清除sessionStorage中的user信息
      sessionStorage.removeItem("user");
    },
    toggleFileSelection({ commit }, { fileId, isSelected, source }) {
      commit("TOGGLE_FILE_SELECTION", { fileId, isSelected, source });
    },

    clearSelectedFiles({ commit }) {
      commit("CLEAR_SELECTED_FILES");
    },
    // 设置parentFolderId的action
    setParentFolderId({ commit }, folderId) {
      commit("SET_PARENT_FOLDER_ID", folderId);
    },
  },
  getters: {
    isLoggedIn: (state) => state.isLoggedIn,
    user: (state) => state.user,
    getSelectedFileIds: (state) => state.selectedFiles.map((file) => file.id),
    // 获取parentFolderId的getter（如果需要的话）
    getParentFolderId: (state) => state.parentFolderId,
  },
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
      // 如果需要，可以指定一个key，但默认会使用模块名作为key前缀
      // key: 'my-app-data'
    }),
  ],
});
